//
//  forgetPassPopView.swift
//  微妙
//
//  Created by DW on 16/9/22.
//  Copyright © 2016年 DW. All rights reserved.
//

import UIKit
import Foundation
import TextFieldEffects
import QorumLogs
import Alamofire

class forgetPassPopView: UIView ,UITextFieldDelegate{
    
    
    @IBOutlet var passLable: AkiraTextField!
    @IBOutlet var titleLable: UILabel!
    @IBOutlet var inputTelNo: AkiraTextField!

    @IBOutlet var confirmLabel: AkiraTextField!
    
    
    
    var sendButton: UIButton!
    var countdownTimer: NSTimer?
    var confirmPassLabel:AkiraTextField!
    var isCheckPage:Bool = true
    var user_Tel:NSString!
    
    var loginBtn:UIButton?
    
    override func awakeFromNib() {
        let width = UIScreen.mainScreen().bounds.width * CGFloat(0.75)
        let height = width * CGFloat(1.5)
        let bgImage = UIImage(named: "popTip_BG")
        let bgView = UIImageView(frame: CGRectMake(0, 0, width, height))
        bgView.image = bgImage
        self.addSubview(bgView)
        //设置数字键盘
        self.passLable.inputView = commonVariable.NUMPAD
        
        self.confirmLabel.hidden = true
        self.initLoginBtn("确认")
        self.addSubview(loginBtn!)
        super.awakeFromNib()
        let sendButtonX = self.passLable.bounds.minX + 20
        sendButton = UIButton()
        sendButton.frame = CGRect(x: 143, y: 132, width: self.bounds.width/8, height: 40)
        sendButton.backgroundColor = UIColor.redColor()
        sendButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        sendButton.setTitle("获取验证码", forState: .Normal)
        sendButton.titleLabel?.font = UIFont.init(name: commonVariable.CHINAFONTNAME, size: 11)
        sendButton.addTarget(self, action: "sendButtonClick:", forControlEvents: .TouchUpInside)
        self.addSubview(sendButton)
        self.confirmLabel.delegate = self
        //申请点击响应
        self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTapBlank:"))
        
    }
    //计数器，倒计时60s的计算
    var remainingSeconds: Int = 0 {
        willSet {
            sendButton.setTitle("\(newValue)  S", forState: .Normal)
            
            if newValue <= 0 {
                sendButton.setTitle("重新获取", forState: .Normal)
                isCounting = false
            }
        }
    }
    
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTime:", userInfo: nil, repeats: true)
                
                remainingSeconds = 60
                
                sendButton.backgroundColor = UIColor.grayColor()
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                
                sendButton.backgroundColor = UIColor.redColor()
            }
            
            sendButton.enabled = !newValue
        }
    }
    //获取验证码的行为
    func sendButtonClick(sender: UIButton) {
        
        //下面获取验证码
        if (self.inputTelNo.text == "" ) {
            SweetAlert().showAlert("请输入您的手机号码")
        }else{
            let telNo = self.inputTelNo.text as! NSString
            SMSSDK.getVerificationCodeByMethod(SMSGetCodeMethodSMS, phoneNumber: telNo as String, zone: "86", result: { (error:NSError!) -> Void in
                if(error == nil){
                    self.isCounting = true
                    QL2("发送成功")
                }else {
                    switch error.code {
                    case 457:
                        SweetAlert().showAlert("您输入的号码有误！")
                    case 477:
                        SweetAlert().showAlert("对不起，当前手机号码今日发送过多，请明日再尝试！")
                    default :
                        SweetAlert().showAlert("出现未知错误！")
                    }
                    QL2("发送失败")
                    QL4(error)
                }
            })
        }
    }
    
    func updateTime(timer: NSTimer) {
        remainingSeconds -= 1
    }
    
    //动态添加按钮
    /**
    方法描述
    
    - returns: 在这个过程中用一个标记来标记现在所在界面是在验证码确认界面还是在输入密码界面，但是使用的btn都是同一个，不过内容不一样
    */
    func initLoginBtn(initStr:NSString){
        let tempX = UIScreen.mainScreen().bounds.width * CGFloat(0.75)/2 - 75
        let tempY = CGFloat(200)
        self.loginBtn = UIButton.init(frame: CGRectMake(tempX + 25, tempY, 100, 34))
        self.loginBtn!.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        self.loginBtn?.setTitle("确 认", forState: UIControlState.Normal)
        self.loginBtn!.titleLabel?.font = UIFont.init(name: commonVariable.CHINAFONTNAME, size: 14)
        self.loginBtn!.backgroundColor = UIColor.init(red: 0.000, green: 0.294, blue: 0.624, alpha: 1.000)
        self.loginBtn!.layer.cornerRadius = 5
        self.loginBtn!.clipsToBounds = true
        self.loginBtn!.addTarget(self, action: "clickBtn", forControlEvents: UIControlEvents.TouchUpInside)
        //注意取消的方法是self.loginBtn.stopAnimating()
    }
    /**
     注意：
     这边对响应事件的判别即通过标示去判别
     */
    func clickBtn(){
        if isCheckPage {
            //下面进行验证
            let telNo = self.inputTelNo.text
            let checkNo = self.passLable.text
            if checkNo == "" {
                SweetAlert().showAlert("请输入验证码！")
            }else{
                SMSSDK.commitVerificationCode(checkNo, phoneNumber: telNo, zone: "86", result: { (error:NSError!) -> Void in
                    if error == nil {
                        //下面所有的语句应该写在alamofire里面，也就是网络返回值是正确值之后
                        self.titleLable.text = "修改密码"
                        self.user_Tel = self.inputTelNo.text
                        QL4(self.user_Tel)
                        self.inputTelNo.text = nil
                        self.inputTelNo.placeholder = "请输入密码"
                        self.inputTelNo.secureTextEntry = true
                        self.passLable.removeFromSuperview()
                        self.sendButton.removeFromSuperview()
                        self.confirmLabel.hidden = false
                        self.confirmLabel.secureTextEntry = true
                        self.isCheckPage = false
                        //标记到了第二个页面
                        self.isCheckPage = false
                        self.initLoginBtn("确认修改")
                        self.addSubview(self.loginBtn!)
                    }else{
                        SweetAlert().showAlert("您输入的验证码有错！")
                    }
                })
            }
            
        }else{
            //说明是第二个界面，那么则修改手机号码对应的密码，修改成功后显示成功界面
            //对用户名和密码进行限制
            if self.confirmLabel.text != ""{
                var length = 0
                for char in self.confirmLabel.text!.characters {
                    // 判断是否中文，是中文+2 ，不是+1
                    length += "\(char)".lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 3 ? 2 : 1
                }
                if length < 8 {
                    SweetAlert().showAlert("密码必须大于8个英文字符")
                    self.confirmLabel.text = ""
                    self.confirmLabel.resignFirstResponder()
                }else if length > 13 {
                    SweetAlert().showAlert("密码不可以大于13个英文字符")
                    self.confirmLabel.text = ""
                    self.confirmLabel.resignFirstResponder()
                }
                return
            }
            //这边需要添加判断两个框是否都有值
            if self.confirmLabel.text == self.inputTelNo.text {
                if self.confirmLabel.text != "" && self.inputTelNo.text != "" {
                    self.titleLable.text = "正在修改"
                    //网络修改用户密码
                    let body = ["userTel":"\(user_Tel!)","userPass":"\(self.confirmLabel.text!)"]
                    Alamofire.request(.POST, commonVariable.EDITUSERPASS,parameters:body as! [String : String],headers:nil).responseJSON() {
                        response in
                        guard let JSONDIC = response.result.value else {
                            QL4(response.result.error)
                            switch response.result.error!.code {
                            case -1009 :
                                SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                            case 3840:
                                SweetAlert().showAlert("对不起", subTitle: "服务出现故障，请联系管理员", style: AlertStyle.Error)
                            case -1001 :
                                
                                SweetAlert().showAlert("对不起", subTitle: "上传信息超时", style: AlertStyle.Error)
                            default:
                                SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                            }
                            return }
                        QL2(JSONDIC)
                        let resultDict = JSONDIC as? NSDictionary
                        let jsonObj = JSON(JSONDIC)
                        let errorCode = jsonObj["errorcode"].intValue
                        let errorMsg = jsonObj["message"].stringValue
                        QL2(errorMsg)
                        if errorCode != 1 {
                            SweetAlert().showAlert("对不起", subTitle: "\(errorMsg)", style: AlertStyle.Warning)
                        }else{
                            self.removeFromSuperview()
                            SweetAlert().showAlert("亲", subTitle: "修改成功!", style: AlertStyle.Success)
                        }
                    }
                }else{
                    SweetAlert().showAlert("亲！请注意", subTitle: "请完善密码框！", style: AlertStyle.Warning)
                }
            }else{
                SweetAlert().showAlert("亲~请注意", subTitle: "两次输入的密码必须相同！", style: AlertStyle.Warning)
            }
            
        }
    }
    //MARK: -textfield代理实现
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    func handleTapBlank(sender: UITapGestureRecognizer) {
        if sender.state == .Ended {
            passLable.resignFirstResponder()
            inputTelNo.resignFirstResponder()
            confirmLabel.resignFirstResponder()
        }
        sender.cancelsTouchesInView = false
    }
    func textFieldDidEndEditing(textField: UITextField) {
        if textField == self.inputTelNo && textField.text != ""{
            var length = 0
            for char in self.inputTelNo.text!.characters {
                // 判断是否中文，是中文+2 ，不是+1
                length += "\(char)".lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 3 ? 2 : 1
            }
            if length < 6 {
                SweetAlert().showAlert("密码必须大于8个英文字符")
                self.inputTelNo.text = ""
                textField.resignFirstResponder()
            }else if length > 12 {
                SweetAlert().showAlert("密码不可以大于13个英文字符")
                self.inputTelNo.text = ""
                textField.resignFirstResponder()
            }
        }
        if textField == self.confirmLabel && textField.text != ""{
            if self.inputTelNo.text != self.confirmLabel.text {
                SweetAlert().showAlert("两次输入的密码必须相同！")
                self.confirmLabel.text = ""
            }
        }
        
    }
    
}